package com.imooc.cart.controller;

import com.imooc.controller.BaseController;
import com.imooc.pojo.IMOOCJSONResult;
import com.imooc.pojo.ShopcartBo;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.RedisOperator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * 购物车
 *
 * @Author: 顾志杰
 * @Date: 2019/12/3
 * @Time: 10:10
 */
@Api(value = "购物车", tags = {"购物车相关的接口"})
@RequestMapping("shopcart")
@RestController
public class ShopcatController extends BaseController {

    @Autowired
    private RedisOperator redisOperator;

    @ApiOperation(value = "添加商品到购物车", notes = "添加商品到购物车", httpMethod = "POST")
    @PostMapping("add")
    public IMOOCJSONResult add(@RequestParam String userId,
                               @RequestBody ShopcartBo shopcartBo,
                               HttpServletRequest request,
                               HttpServletResponse servletResponse) {
        if (StringUtils.isBlank(userId)) {
            return IMOOCJSONResult.errorMsg("");
        }

        // 前端用户在登录的情况下，添加商品到购物车，会同时在后端同步购物车到redis缓存
        // 需要判断当前购物车中包含已经存在的商品 如果存在则累加商品数量
        String shopcatJson = redisOperator.get(FOODIE_SHOPCART + ":" + userId);
        List<ShopcartBo> shopcartBos = null;
        if (StringUtils.isNotBlank(shopcatJson)) {
            //redis中已经有购物车
            shopcartBos = JsonUtils.jsonToList(shopcatJson, ShopcartBo.class);
            //判断购物车中是否存在已有商品，如果有的话conts累加
            AtomicBoolean isHaving = new AtomicBoolean(false);
            Objects.requireNonNull(shopcartBos).stream()
                    .filter(shopcat -> shopcat.getSpecId().equals(shopcartBo.getSpecId()))
                    .forEach(shopcat -> {
                        shopcat.setBuyCounts(shopcat.getBuyCounts() + shopcartBo.getBuyCounts());
                        isHaving.set(true);
                    });
            if (!isHaving.get()) {
                shopcartBos.add(shopcartBo);
            }
        } else {
            shopcartBos = new ArrayList<>();
            shopcartBos.add(shopcartBo);
        }
        redisOperator.set(FOODIE_SHOPCART + ":" + userId, JsonUtils.objectToJson(shopcartBos));
        System.out.println(shopcartBo.toString());
        return IMOOCJSONResult.ok();
    }


    @ApiOperation(value = "从购物车删除商品", notes = "从购物车删除商品", httpMethod = "POST")
    @PostMapping("del")
    public IMOOCJSONResult del(@RequestParam String userId,
                               @RequestParam String itemSpecId,
                               HttpServletRequest request,
                               HttpServletResponse servletResponse) {
        if (StringUtils.isBlank(userId)) {
            return IMOOCJSONResult.errorMsg("");
        }
        // 前端用户在登录的情况下，从购物车删除商品，会同时在后端redis缓存中删除商品
        String shopcatJson = redisOperator.get(FOODIE_SHOPCART + ":" + userId);
        if (StringUtils.isNotBlank(shopcatJson)) {
            //redis中已经有购物车
            List<ShopcartBo> shopcartBos = JsonUtils.jsonToList(shopcatJson, ShopcartBo.class);
            assert shopcartBos != null;
            shopcartBos.stream()
                    .filter(shopcartBo -> itemSpecId.equals(shopcartBo.getSpecId()))
                    .collect(Collectors.toList())
                    .forEach(shopcartBos::remove);
            //覆盖现有redis中的购物车
            redisOperator.set(FOODIE_SHOPCART + ":" + userId, JsonUtils.objectToJson(shopcartBos));
        }
        return IMOOCJSONResult.ok();
    }
}
